-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.c
More file actions
68 lines (58 loc) · 1.35 KB
/
Solution.c
File metadata and controls
68 lines (58 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void append(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
int isPalindrome(Node* head) {
Node *slow = head, *fast = head, *prev = NULL, *temp;
while (fast && fast->next) {
fast = fast->next->next;
temp = slow->next;
slow->next = prev;
prev = slow;
slow = temp;
}
if (fast) slow = slow->next;
while (slow) {
if (slow->data != prev->data) return 0;
slow = slow->next;
prev = prev->next;
}
return 1;
}
int main() {
Node* head = NULL;
int n, val;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &val);
append(&head, val);
}
if (isPalindrome(head)) {
printf("The linked list is a palindrome.\n");
} else {
printf("The linked list is not a palindrome.\n");
}
return 0;
}